package com.easylinkin.linkappapi.common.utils.message;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.easylinkin.linkappapi.alarm.entity.AlarmNotice;
import com.easylinkin.linkappapi.alarm.service.AlarmNoticeService;
import com.easylinkin.linkappapi.alarm.service.impl.AlarmNoticeServiceImpl;
import com.easylinkin.linkappapi.elasticsearch.entity.BankAlarmNotice;
import com.easylinkin.linkappapi.elasticsearch.mapper.BankAlarmNoticeMapper;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


/**
 * @Description 发送邮件的
 * @ClassName SendEmailUtil
 * @Author 徐国庆
 * @date 2020.05.15 13:39
 */
@Component
public class SendEmailUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailUtil.class);
    private static final Integer SUCCESS = 1;
    @Autowired
    private MimeMessageHelper mimeMessageHelper;
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Autowired
    private BankAlarmNoticeMapper bankAlarmNoticeMapper;

    @Autowired
    @Qualifier("freeMarkerConfiguration")
    private Configuration freemarkerConf;

    @Autowired
    private AlarmNoticeService alarmNoticeService;

    @Async
    public void sendEmailAndSaveAlarmNotice(List<AlarmNotice> alarmNoticeList) {
        if (ObjectUtils.isEmpty(alarmNoticeList)) {
            return;
        }
        for (AlarmNotice alarmNotice : alarmNoticeList) {
            boolean flag;
            try {
                alarmNotice.setSendTime(new Date());
                alarmNotice.setMessageType(AlarmNoticeServiceImpl.EMAIL_TYPE);
                alarmNotice.setMessageWay(alarmNotice.getEmailAddress());
                Template template = this.createTemplate(alarmNotice.getTempletId(), alarmNotice.getTempleteMailContent());
                String text = alarmNotice.getEmailBodyText(template);
                flag = send(Collections.singletonList(alarmNotice.getEmailAddress()).toArray(new String[1]), text, null);
            }  catch (IOException e) {
                LOGGER.error("get template   fail!", e);
                flag = false;
            } catch (TemplateException e) {
                LOGGER.error("parse  template   fail!", e);
                flag = false;
            }
            if (flag) {
                alarmNotice.setStatus(SUCCESS);
                alarmNoticeService.save(alarmNotice);
            }
        }
    }


    /**
     * 发送邮件
     *
     * @param to   发送地址
     * @param text 发送信息
     */
    public boolean send(String[] to, String text, String subject) {
        try {
            if (subject != null) {
                mimeMessageHelper.setSubject(subject);
            }
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setText(text, true);
            mimeMessageHelper.setSentDate(new Date());
            MimeMessage message = mimeMessageHelper.getMimeMessage();
            javaMailSender.send(message);
        } catch (MessagingException e) {
            LOGGER.error("邮件发送失败", e);
            return false;
        }
        return true;
    }

    @Async
    public void sendBankEmail(BankAlarmNotice bankAlarmNotice) {
        boolean flag = true;
        if (StringUtils.isEmpty(bankAlarmNotice.getEmailAddress())) {
            return;
        }
        LOGGER.info("产生的告警入库数据" + bankAlarmNotice.toString());
        bankAlarmNoticeMapper.insert(bankAlarmNotice);
        try {
            mimeMessageHelper.setTo(bankAlarmNotice.getEmailAddress());
            Template templet = this.createTemplate(bankAlarmNotice.getTempletId(), bankAlarmNotice.getTempleteMailContent());
            String text = bankAlarmNotice.getBankEmaiBodyText(templet);
            mimeMessageHelper.setText(text, true);
            mimeMessageHelper.setSentDate(new Date());
            MimeMessage message = mimeMessageHelper.getMimeMessage();
            javaMailSender.send(message);
        } catch (MessagingException e) {
            LOGGER.error("initial message  fail!",e);
            flag = false;
        } catch (IOException e) {
            LOGGER.error("get templet   fail!",e);
            flag = false;
        } catch (TemplateException e) {
            LOGGER.error("parse  templet   fail!",e);
            flag = false;
        } catch (MailSendException e) {
            LOGGER.error("send  message   fail!",e);
            flag = false;
        }
        if (flag) {
            bankAlarmNotice.setStatus(SUCCESS);
            bankAlarmNoticeMapper.updateById(bankAlarmNotice);
        }
    }

    /**
     * freeMaker通过字符串创建模板 freeMarkerConfiguration 中会加载freemaker模板
     */
    private Template createTemplate(String name, String templateContent) throws IOException {
        Template template = freemarkerConf.getTemplate(name, (Locale) null, (Object) null, "utf-8", true, true);
        if (template != null) {
            return template;
        }
        synchronized (this) {
            TemplateLoader templateLoader = freemarkerConf.getTemplateLoader();
            if (templateLoader != null && templateLoader instanceof StringTemplateLoader) {
                ((StringTemplateLoader) templateLoader).putTemplate(name, templateContent);
                freemarkerConf.setTemplateLoader(templateLoader);
            } else {
                StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
                stringTemplateLoader.putTemplate(name, templateContent);
                freemarkerConf.setTemplateLoader(stringTemplateLoader);
            }
            freemarkerConf.clearTemplateCache();
            template = freemarkerConf.getTemplate(name, "utf-8");
            return template;
        }
    }


}

